<?php
/**
 *  * author 韩天尊
 * Date: 2022/3/15
 * Email: <724700483@qq.com>
 */

namespace App\Toolys;

class Rsa
{

    public static function createRsa(): object
    {
        $config = array(
            "digest_alg"    => "sha512",
            "private_key_bits" => 4096,           //字节数  512 1024 2048  4096 等 ,不能加引号，此处长度与加密的字符串长度有关系，可以自己测试一下
            "private_key_type" => OPENSSL_KEYTYPE_RSA,   //加密类型
        );
        $res =    openssl_pkey_new($config);
        //提取私钥
        openssl_pkey_export($res, $private_key);
        //生成公钥
        $public_key = openssl_pkey_get_details($res);
        $public_key=$public_key["key"];
        return arrayTransitionObject(["private_key"=>$private_key, "public_key"=>$public_key]);
    }


    /** 加密
     * @param string $str
     * @param string $key
     * @param $keyType false 私钥加密  true 公钥加密
     */
    public static function encode(string $str, bool $keyType=false): string
    {
        $ins = \EasySwoole\EasySwoole\Config::getInstance();
        $key = $keyType?$ins->getConf("APP_DATA.RSA.public"):$ins->getConf("APP_DATA.RSA.private");
        $keyType?openssl_public_encrypt($str, $encrypted, $key):openssl_private_encrypt($str,$encrypted, $key);
        $encrypted = base64_encode($encrypted);
        $hint = ($keyType?'公钥':'私钥')."加密";
        print_r("{$hint} => {$encrypted}");echo PHP_EOL;
        return $encrypted;
    }

    /**
     * @param string $str
     * @param string $key
     * @param bool $keyType false 私钥解密  true 公钥解密
     */
    public static function decode(string $str, bool $keyType=false){
        $ins = \EasySwoole\EasySwoole\Config::getInstance();
        $key = $keyType?$ins->getConf("APP_DATA.RSA.public"):$ins->getConf("APP_DATA.RSA.private");
        $keyType?openssl_public_decrypt(base64_decode($str), $decrypted, $key):openssl_private_decrypt(base64_decode($str), $decrypted, $key);
        $hint = ($keyType?'公钥':'私钥')."解密";
        print_r("{$hint} => {$decrypted}");echo PHP_EOL;
        return $decrypted;
    }
}